import Vue from 'vue'
import { CustomToolTip } from '@/components/common/CustomToolTip.js'

Vue.directive('tooltip', {
  /**
   * 当被绑定的元素插入到 DOM 中时绑定事件
   * modifiers:parent(true代表判断是否显示弹框时新增元素与绑定元素的父元素比较宽度)
   */
  inserted: function (el, binding) {
    /**
     *显示tooltip
     * @param {String} text 文本
     * @param {*} el 指令绑定的元素
     * @param {*} e 事件
     */
    function showPop (text, el, event) {
      let target = event.target
      if (target !== el.parentNode) {
        return
      }
      el._brotherNpde.innerHTML = el.innerHTML
      let compareEl = el
      if (el.modifiers.parent) {
        compareEl = el.parentNode
      }
      // 若新增的兄弟节点宽度大于当前元素则显示提示框
      if (el._brotherNpde.getBoundingClientRect().width > compareEl.getBoundingClientRect().width) {
        CustomToolTip.show({
          el: target,
          text: el.innerHTML
        })
      }
    }

    /**
     *隐藏tooltip
     * @param {*} el 指令绑定的元素
     * @param {*} event 事件
     */
    function closePop (el, event) {
      let target = event.target
      if (target !== el.parentNode) {
        return
      }
      if (!target.contains(event.toElement)) {
        CustomToolTip.close()
      }
    }

    // 记录绑定事件，用于解绑
    el._vueShowPop = showPop
    el._vueclosePop = closePop

    let parentNode = el.parentNode

    // 新增兄弟节点用于判断当前文字是否是ellipsis
    let span = document.createElement('span')
    span.style.visibility = 'hidden'
    span.style.position = 'absolute'
    span.style.zIndex = '-1'
    span.style.whiteSpace = 'nowrap'
    span.innerHTML = binding.value
    parentNode.appendChild(span)
    el._brotherNpde = span
    el.modifiers = binding.modifiers || {}
    // console.log(binding)

    parentNode.addEventListener('mouseenter', el._vueShowPop.bind(this, binding.value, el))
    parentNode.addEventListener('mouseleave', el._vueclosePop.bind(this, el))
  },
  // 解绑事件，删除新增dom
  unbind: function (el) {
    CustomToolTip.close()
    let parentNode = el.parentNode
    el._brotherNpde && parentNode.removeChild(el._brotherNpde)
    parentNode.removeEventListener('mouseenter', el._vueShowPop)
    parentNode.removeEventListener('mouseleave', el._vueclosePop)
    el._brotherNpde = null
    el._vueShowPop = null
    el._vueclosePop = null
  }
})
